package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"onerk4/zg5yk/ordering/common/proto/takeout"
)

type TakeoutHandler func(ctx context.Context, in takeout.TakeoutClient) (interface{}, error)

func TakeoutClient(ctx context.Context, handler TakeoutHandler) (interface{}, error) {
	// 1.连接
	conn, err := grpc.Dial("127.0.0.1:8081", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
		return nil, err
	}
	defer conn.Close()
	c := takeout.NewTakeoutClient(conn)
	res, err := handler(ctx, c)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func ShowTakeoutList(ctx context.Context, req *takeout.ShowTakeoutListRequest) (*takeout.ShowTakeoutListResponse, error) {
	client, err := TakeoutClient(ctx, func(ctx context.Context, in takeout.TakeoutClient) (interface{}, error) {
		login, err := in.ShowTakeoutList(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*takeout.ShowTakeoutListResponse), nil
}

func UserRecommend(ctx context.Context, req *takeout.UserRecommendRequest) (*takeout.UserRecommendResponse, error) {
	client, err := TakeoutClient(ctx, func(ctx context.Context, in takeout.TakeoutClient) (interface{}, error) {
		login, err := in.UserRecommend(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*takeout.UserRecommendResponse), nil
}
